package com.qfmy.web.app.task;

import com.qfmy.model.entity.user.UserInfo;
import com.qfmy.web.app.mapper.user.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 清风明月
 * @Package com.qfmy.web.app.task
 * @date 2025/11/1
 * @description 用户定时任务
 */
@Component
public class UserInfoTask {

    /**
     * 注入redisTemplate
     */
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;


    /**
     * 注入用户mapper
     */
    @Autowired
    private UserMapper userMapper;

    /**
     * 每天凌晨清除用户昨天阅读时间
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void clearYesterdayReadTime() {
        redisTemplate.delete("today_read_time:*");
    }

    /**
     * 更新用户的vip状态
     */
    @Scheduled(cron = "0 0 0 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void updateUserVipStatus() {
        //获取所有的用户
        List<UserInfo> users = userMapper.getAllUsers();
        //创建一个集合，用于存储用户的id
        List<Long> userIds = new ArrayList<>();
        for (UserInfo user : users) {
            //获取用户的vip到期时间
            LocalDateTime vip = user.getVipExpired();
            //如果为null，则跳过
            if(vip == null) continue;
            //判断是否到期
            if(vip.isBefore(LocalDateTime.now()))
            {
                //添加过期用户的id
                userIds.add(user.getUserId());
            }
        }
        //批量更新用户的vip状态
        userMapper.updateUserVipStatus(userIds);
    }

}
